package myArrayList;

import java.util.Arrays;

public class MyArrayList implements IList{
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_SIZE=10;
    public MyArrayList(){
        elem=new int[DEFAULT_SIZE];
    }
    public MyArrayList(int captic){
        elem=new int[captic];
    }

    /*
    首先考虑是否需要扩容
     */
    public boolean isFull(){
        return usedSize==elem.length;
    }
    private void checkDilatation(){
        if(isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
    }
    @Override
    public void add(int data) {
        checkDilatation();

        elem[usedSize]=data;
        usedSize++;
    }
    /*
    1.判断pos是否合法
    2.将data放到pos位置
    3.usedSize++;
     */
    public void posLegal(int pos) throws isLeal{
        if(pos<0||pos>usedSize){
            System.out.println("不合法");
            throw new isLeal("下标不合法"+pos);
        }
    }
    @Override
    public void add(int pos, int data) {
            try {
                posLegal(pos);
            }catch (isLeal e){
                e.printStackTrace();
            }
            checkDilatation();
        for (int i = usedSize-1; i < pos; i--) {
            elem[i+1]=elem[i];
        }
        elem[pos]=data;
        usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }
    public void posLegalGetAndSet(int pos) throws PosLegislation{
        if(pos<0||pos>=usedSize){
            System.out.println("不合法");
            throw new isLeal("元素下标异常");
        }
    }
    @Override
    public int get(int pos) {
        try {
            posLegalGetAndSet(pos);
        }catch (PosLegislation e){
            e.printStackTrace();
        }
        return elem[pos];
    }

    @Override
    public void set(int pos, int value)throws PosLegislation {
        try {
            posLegalGetAndSet(pos);
        }catch (PosLegislation e){
            e.printStackTrace();
        }

        elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int index=indexOf(toRemove);
        if(index==-1){
            return;
        }
        for (int i = index; i < usedSize-1; i++) {
            elem[i]=elem[i+1];
        }

    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        this.usedSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
}
